package com.mach.platform.service;

import com.mach.platform.domain.iot.IotCollItem;
import com.mach.platform.repository.IotCollItemRepo;
import com.mach.platform.utils.springdata.DynamicSpecifications;
import com.mach.platform.utils.springdata.SearchFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Anonymous
 * @Description: 设备库 服务类
 * @Package: com.mach.platform.service
 * @time 2018/04/27 23:11
 */
@Slf4j
@Service
public class IotCollItemServiceImpl implements BaseService<IotCollItem> {

	@Autowired
	private IotCollItemRepo collItemRepo;

	/**
	 * 查询母线设备类型的全部属性
	 * @return
	 */
	public List busDevItems() {
		List<String> itemList = collItemRepo.findNamesByDevTypeId();
		List<Map> result = new ArrayList<>();
		Map map;
		for (String item : itemList) {
			map = new HashMap();
			map.put("value", item);
			map.put("label", item);
			result.add(map);
		}
		return result;
	}


	/**
	 * 保存
	 *
	 * @param coll 保存的实体
	 * @return T 返回保存后的实体
	 */
	@Transactional(rollbackOn = Exception.class)
	@Override
	public IotCollItem save (IotCollItem coll) {

		IotCollItem dbResult = collItemRepo.saveAndFlush(coll);

		return dbResult;
	}

	/**
	 * 插入，批量保存
	 *
	 * @param list 实体集合
	 * @return List<T>
	 */
	@Override
	public List<IotCollItem> insertObjInBatch (List<IotCollItem> list) {
		return null;
	}

	/**
	 * 更新
	 *
	 * @param device 跟新的实体
	 * @return T
	 */
	@Transactional(rollbackOn = Exception.class)
	@Override
	public IotCollItem update (IotCollItem device) {

		IotCollItem dbResult = collItemRepo.saveAndFlush(device);

		return dbResult;
	}

	/**
	 * 删除--批量删除
	 *
	 * @param ids 批量删除id
	 * @return int 影响数
	 */
	@Transactional(rollbackOn = Exception.class)
	@Override
	public int delete (Long[] ids) {
		return collItemRepo.deleteByIdIn(ids);
	}

	/**
	 * 获取列表数据---使用 com.mach.platform.utils.springdata  下的DynamicSpecifications 的
	 * 写法进行分页查询
	 *
	 * @param pageable 分页参数
	 * @param params   其他参数
	 * @return Page<T>
	 */
	@Override
	public Page<IotCollItem> list (Pageable pageable, Map params) {

		Specification specification = DynamicSpecifications
				                              .bySearchFilter(SearchFilter.parse(params).values(), IotCollItem.class);

		return collItemRepo.findAll(specification, pageable);
	}

	/**
	 * 获取单体 数据
	 *
	 * @param id 获取详情的id
	 * @return T
	 */
	@Override
	public IotCollItem info (Long id) {
		return collItemRepo.getById(id);
	}
}
